package com.guxingke.typecho4j.widget.provider.content;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.guxingke.typecho4j.jfinal.model.Content;
import com.guxingke.typecho4j.util.PageBean;
import com.guxingke.typecho4j.util.PageUtil;
import com.guxingke.typecho4j.widget.WidgetProvider;
import com.guxingke.typecho4j.widget.provider.ContentBaseWidget;
import com.jfinal.core.Controller;

/**
 * 默认首页的主内容组件<br>
 * 
 * @author guxingke
 * */
public class IndexPostsWidget extends ContentBaseWidget implements
		WidgetProvider {
	private Map<Integer, List<Content>> indexPostsCache = new HashMap<Integer, List<Content>>();

	@Override
	public void excute(Controller controller) {
		Integer page = controller.getParaToInt("page");
		Integer pageSize = constants.getPageSize();
		if (page == null) {
			page = 1;
		}

		List<Content> posts = getIndexPosts(new PageBean(page, pageSize));
		controller.setAttr("posts", posts);

		// TODO
		String pageNav = PageUtil.getPagation(constants.getSiteUrl()
				+ "/index", 10, page, pageSize);
		controller.setAttr("pageNav", pageNav);
	}

	@Override
	public void refresh() {
		// 重置缓存
		this.indexPostsCache.clear();
	}

	private List<Content> getIndexPosts(PageBean pageBean) {
		int page = pageBean.getPage();
		if (indexPostsCache.containsKey(page)) {
			return indexPostsCache.get(page);
		}
		List<Content> results = getPosts(pageBean);
		indexPostsCache.put(page, results);
		return results;
	}
}
